package controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
 * @author ：Teacher陈(86521760@qq.com)
 * @date ：Created in 2022/3/28 16:04
 * @description：字符编码过滤器
 * @modified By：
 * @version: 1.0
 */
@WebFilter(urlPatterns = "/*")
public class EncodeFilter implements Filter {
   private  String encode="UTF-8";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        String parameter = servletContext.getInitParameter("encode");
        if(null!=parameter&&parameter.length()>0){
            encode=parameter;
        }
        System.out.println("字符编码过滤器初始化了");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //开始过滤，字符编码
        //设置编码格式
        System.out.println("字符编码开始工作了");
        servletRequest.setCharacterEncoding(encode);
        servletResponse.setContentType("application/json");
        servletResponse.setCharacterEncoding(encode);
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {
        System.out.println("字符编码过滤器销毁了");
    }
}
